<?php
declare(strict_types=1);

namespace app\command;

use app\common\model\order\ShopOrderModel;
use app\common\service\order\ShopOrderService;
use app\common\service\system\SettingService;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Log;
use think\facade\Queue;

/**
 * 操作订单超时回池
 * 调试模式开启：php think orderRevoke
 * 守护进程开启：php think orderRevoke -m d
 */
class OrderRevoke extends Command
{

    protected function configure()
    {
        // 指令配置
        $this->setName('orderRevoke')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addOption('mode', 'm', Option::VALUE_OPTIONAL, '守护进程方式启动（-m d）')
            ->addOption('interval', 'i', Option::VALUE_OPTIONAL, '多长时间执行一次（秒）')
            ->setDescription('操作订单超时回池');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('orderRevoke:execute');

        Log::write("操作订单超时回池：".date('Y-m-d H:i:s'));
        try {
            $setting = SettingService::info('order_operating_time');
            if($setting['order_operating_time']>0){
                $time = date('Y-m-d H:i:s', strtotime('-'.$setting['order_operating_time'].' minutes'));
                $where =[
                    ['is_delete','=',0],
                    ['status','=',ShopOrderModel::getStatus('o_operation',1)],
                    ['meet_time','<=',$time]
                ];
                $list = ShopOrderService::getList($where,0,0,['meet_time'=>'asc'],'id,member_id');
                if($list){
                    Log::write("操作订单超时回池数量：".count($list)."，订单ID".implode(',',array_column($list,'id')));
                    foreach ($list as $key=>$val){
                        $data = ShopOrderService::cancelOrderByOperation($val['id'],['member_id'=>$val['member_id']],'系统自动回池');
                    }
                }
            }
        } catch (\Exception $e) {
            Log::error("操作订单超时回池报错：".$e->getMessage());
        }
    }


    public function stop()
    {
    }


}
